import type { Effect, Reducer } from 'umi';
import { queryCurrent, currentCorpList, getPerm } from '@/services/user';
import { getCookie } from '@/utils/utils';
//用户信息，所以端都会使用该type，接口调用大部分不需要判断，但是类似消息在未进入具体端(消息在最外层调用)
//使用system判断当前登录是哪个端
export type CurrentUser = {
  attrs?: {
    departmentId: number;
    departmentName: string;
  };
  avatar?: string;
  name?: string;
  currentMobile?: string;
  certNo?: string;
  title?: string;
  group?: string;
  signature?: string;
  tags?: {
    key: string;
    label: string;
  }[];
  userId?: string;
  tag?: number;
  status?: number;
  unreadCount?: number;
  perms?: any[]; //路由及按钮权限，施工端有些是前端自己控制，具体看下面获取用户信息中代码
  system?: 'cm' | 'bk' | 'ls' | 'gs'; //施工，银行，劳监, 担保
  bankName?: string;
  bankId?: string;
  bankType?: number; //1:担保公司 2:保险公司 3:平台
  corps?: any[];
  selectCorpId?: string; //
  selectCorp?: any;
  selectType?: string; //1:施工单位,2:建设单位,3:劳务公司
};

export type UserModelState = {
  currentUser?: CurrentUser;
};

export type UserModelType = {
  namespace: 'user';
  state: UserModelState;
  effects: {
    fetchCurrent: Effect;
    setUser: Effect;
    clearUser: Effect;
    setSelectCorp: Effect;
  };
  reducers: {
    saveCurrentUser: Reducer<UserModelState>;
    clearCurrentUser: Reducer<UserModelState>;
    changeSelectCorp: Reducer<UserModelState>;
    changeNotifyCount: Reducer<UserModelState>;
  };
};

const UserModel: UserModelType = {
  namespace: 'user',

  state: {
    currentUser: {},
  },

  effects: {
    *fetchCurrent({ payload }, { call, put }): any {
      const res = yield call(queryCurrent, payload);
      if (res.success) {
        const par = {
          system: payload.type,
          ...res.data,
        };
        if (payload.type == 'cm') {
          //type为调用传入
          //如果为施工端，需要先获取当前企业信息
          // const cid = window.sessionStorage.getItem('corpId');
          // const ctype = window.sessionStorage.getItem('corpType');
          const cid = getCookie('currentCorpId');
          const ctype = getCookie('currentCorpType');
          //获取企业列表，可能有多个，需要弹窗切换
          const corp = yield call(currentCorpList);
          if (corp.success) {
            if (corp.data) {
              par.corps = corp.data || [];
            }
          }
          if (cid && ctype) {
            //如果有记录，说明登录过，判断企业类型
            //获取用户信息、权限
            const resPerm1 = yield call(getPerm);
            let newPerm1 = [];
            if (resPerm1 && resPerm1.success) {
              newPerm1 = resPerm1.data.perms || [];
            }
            par.selectCorpId = cid;
            par.selectType = ctype;
            if (ctype == '1') {
              //施工单位
              par.perms = ['CM_MANAGER_PROJECT', 'CM_MANAGER_USER', 'CM_MANAGER_LOAN'];
            } else if (ctype == '2') {
              //, 'CM_MANAGER_SYSTEM'
              //业主单位
              const per = par.perms || [];
              par.perms = [...per, ...newPerm1, 'CM_MANAGER_PROJECT', 'CM_MANAGER_USER'];
            } else {
              par.perms = ['CM_MANAGER_PROJECT'];
            }
          } else if (par.corps && par.corps.length === 1) {
            //只要一个企业，判断企业类型
            const resPerm2 = yield call(getPerm);
            let newPerm2 = [];
            if (resPerm2 && resPerm2.success) {
              newPerm2 = resPerm2.data.perms || [];
            }
            const t = par.corps[0].type;
            const sid = par.corps[0].id;
            par.selectType = t + '';
            par.selectCorpId = sid;
            if (Number(t) == 1) {
              par.perms = ['CM_MANAGER_PROJECT', 'CM_MANAGER_USER', 'CM_MANAGER_LOAN'];
            } else if (Number(t) == 2) {
              //, 'CM_MANAGER_SYSTEM'
              const per = par.perms || [];
              par.perms = [...per, ...newPerm2, 'CM_MANAGER_PROJECT', 'CM_MANAGER_USER'];
            } else {
              par.perms = ['CM_MANAGER_PROJECT'];
            }
          } else {
            //没有企业，说明未认证，默认进入施工单位
            par.selectType = '1';
            const per = par.perms || [];
            par.perms = [...per, 'CM_MANAGER_PROJECT', 'CM_MANAGER_USER', 'CM_MANAGER_LOAN'];
          }
        }
        yield put({
          type: 'saveCurrentUser',
          payload: par,
        });
      } else {
        yield put({
          type: 'saveCurrentUser',
          payload: {},
        });
      }
    },
    *setUser({ payload }, { put }) {
      yield put({
        type: 'saveCurrentUser',
        payload: payload,
      });
    },
    *clearUser({}, { put }) {
      window.sessionStorage.removeItem('corpId');
      window.sessionStorage.removeItem('corpType');
      window.sessionStorage.clear();

      yield put({
        type: 'clearCurrentUser',
        payload: {},
      });
    },
    *setSelectCorp({ payload }, { put, select, call }): any {
      //切换企业，需要根据切换的类型修改对应的权限
      //因为施工端权限由前端根据后端给的企业类型转换
      const condition = yield select((state: any) => {
        return state.user;
      });
      let pState = condition.currentUser?.perms || [];
      // const res = yield call(getPerm);
      // if (res && res.success) {
      //   const par = res.data.perms || [];
      //   pState = [...pState, ...par];
      // }
      let perms: any[] = [''];
      if (payload.selectCorp) {
        if (payload.selectCorp.type == '1') {
          perms = ['CM_MANAGER_PROJECT', 'CM_MANAGER_USER', 'CM_MANAGER_LOAN'];
        } else if (payload.selectCorp.type == '2') {
          //, 'CM_MANAGER_SYSTEM'
          perms = [...pState, 'CM_MANAGER_PROJECT', 'CM_MANAGER_USER'];
        } else {
          perms = ['CM_MANAGER_PROJECT'];
        }
      }
      //记录当前使用的企业
      window.sessionStorage.setItem('corpId', payload.selectCorpId);
      window.sessionStorage.setItem('corpType', payload.selectCorp.type + '');
      yield put({
        type: 'changeSelectCorp',
        payload: {
          selectCorpId: payload.selectCorpId,
          selectCorp: payload.selectCorp,
          selectType: payload.selectCorp.type,
          perms,
        },
      });
    },
  },

  reducers: {
    saveCurrentUser(state, { payload }) {
      //保存用户信息
      //同样有些路由权限是由前端自己转换
      if (payload && !payload.perms) {
        payload.perms = [''];
      }
      if (payload && payload.attrs) {
        //判断扩展信息
        //银行、担保公司需要展示信息在右上角
        if (payload.attrs.thirdPlatformId) {
          payload.bankId = payload.attrs.thirdPlatformId;
        }
        if (payload.attrs.thirdPlatformName) {
          payload.bankName = payload.attrs.thirdPlatformName;
        }
        if (payload.attrs.type) {
          //1:担保公司 2:保险公司 3:平台
          payload.bankType = payload.attrs.type;
          if (payload.bankType == 1 && payload.perms.indexOf('TP_MARGIN_ACCOUNT_MANAGER') > -1) {
            //'GU_LOAN_MANNAGER',
            payload.perms = ['GU_ORDER_LIST', ...payload.perms];
          } else if (
            payload.bankType == 2 &&
            payload.perms.indexOf('TP_MARGIN_ACCOUNT_MANAGER') > -1
          ) {
            payload.perms = ['GU_ORDER_LIST', ...payload.perms];
          } else if (payload.bankType == 3) {
            // payload.perms = ['GU_LOAN_MANNAGER', ...payload.perms];
          }
        }
        if (payload.attrs.bankName) {
          payload.bankName = payload.attrs.bankName;
        }
        if (payload.attrs.bankId) {
          payload.bankId = payload.attrs.bankId;
        }
        if (payload.attrs.mainBank == true) {
          if (payload.perms.indexOf('BANK_BRANCH_MANAGER') > -1) {
            payload.perms = [...payload.perms, 'BANK_CHILD_MANAGER'];
          } else {
            payload.perms = payload.perms.filter((item: any) => item != 'BANK_CHILD_MANAGER');
          }
        } else {
          payload.perms = payload.perms.filter((item: any) => item != 'BANK_CHILD_MANAGER');
        }
      }

      return {
        ...state,
        currentUser: payload || {},
      };
    },
    clearCurrentUser(state, { payload }) {
      return {
        ...state,
        currentUser: payload || {},
      };
    },
    changeSelectCorp(
      state = {
        currentUser: {},
      },
      action,
    ) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          selectCorpId: action.payload.selectCorpId,
          selectCorp: action.payload.selectCorp,
          selectType: action.payload.selectType,
          perms: action.payload.perms,
        },
      };
    },
    changeNotifyCount(
      state = {
        currentUser: {},
      },
      action,
    ) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
  },
};

export default UserModel;
